const app = getApp();
import { hbappRequest, jiatuiRequest } from "/utils/requests";
Page({
    data: {
        showContact: true,
        suspendShow: true,
        showIcon: true,
        bgcolor: '',
        wenda: [],
        shai: [],
        gonghao: "无",
        fenxiao: "无",
        laiyuan: "资料库",
        isShowCdNav: !1,
        jilu: "",
        myPhone: "",
        backtop: 0,
        backWidth: 0,
        backHeight: 0,
        xiangmu: "sk",
        _id: "2021gkbps",
        fp: "n",
        flag: !1,
        houzhui: "hb",
        add: !1,
        array: ["大一", "大二", "大三", "大四"],
        index: 0,
        marginTop: 0,
        yl: 1,
        bookDetails_box: !1,
        isSydw: false,
        isYiShi: false,
        addFriends: false,
        book: '',
        bj_img: '',
        gwlb: null,
        // 同程协作轮播及底部按钮
        bpslunbo: false,
        isShowAuth: !1,
        isShowAuth2: !1,
        wangke: false,
        inputPhone: false,
        ziliao: undefined,
    },
    onLoad: async function (options) {
        this.setData(await app.methods.myPhone()); // 获取本地存储手机号
        if(!this.data.myPhone) {
            await app.methods.getPhoneNumber()
            this.setData({
              isShowAuth: !0
            })
        }
        xhs.showLoading({
            title: '数据加载中....',
            mask: true
        })
        xhs.showShareMenu({
          shareTypes: 'normal',
        })
        let links, jxOptions;
        if (options.scene) {
            options.scene = options.scene.replace(/%253D/g, ".");
            options.scene = options.scene.replace(/%2526/g, "-");
            jxOptions = await app.methods.getOPtions(options);
        }
        let id = options.scene ? jxOptions.id : options.id;
        options.id = id;
        links = await app.methods.getLink(id);
        options._id = links._id ? links._id : '';
        options.yl = links.yl ? links.yl : '';
        options.fx = options.scene ? jxOptions.fx : options.fx;
        options.gh = options.scene ? jxOptions.gh : options.gh;
        if(links.actid) options.actid = links.actid;
        let xiangmu = options._id;
        if (xiangmu.indexOf('sydw') >= 0) {
            this.setData({
                isSydw: true
            })
        } else if (xiangmu.indexOf('yishi') >= 0) {
            this.setData({
                isYiShi: true
            })
        }
        if (options.yl != undefined) {
            if (options.yl.length > 0) {
                this.setData({
                    yl: Number(options.yl)
                })
            }
        }
        this.setData({
            _id: options._id,
            options: options
        })
        await this.getHdInfo(this.data.options._id)
        await this.getShareInfo(this.data.options._id)
        this.setData(await app.methods.getIdentity(options)); // 获取个人身份信息
        if(this.data.getIdentity.crm) {
            options.wxh = this.data.getIdentity.crm;
        } else {
            options.wxh = options.gh;
        }
        this.setData(await app.methods.getWechat(options)); // 获取个人身份信息
        this.setData(await app.methods.guishudi(options)); // 获取归属地
        let fenbu = this.data.fenbu;
        let fenxiao = this.data.fenxiao;
        let getIdentity = this.data.getIdentity;
        getIdentity.fenbu = fenbu;
        getIdentity.fenxiao = fenxiao;
        getIdentity.zzname = this.data.zzname;
        getIdentity.zzid = this.data.zzid;
        getIdentity.erpdqm = this.data.erpdqm;
        this.setData({
            options: options,
            navTop: app.globalData.navTop,
            navHeight: app.globalData.navHeight - app.globalData.navTop,
            getIdentity: getIdentity
        })
        if(this.data.myPhone) {
            this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'))
            if (!this.data.user) {
                if (this.data.isSydw) {
                    this.setData({
                        bookDetails_box: 1
                    })
                } else {
                    await app.methods.registerCX(this.data.myPhone, this.data.options.actid, this.data.name1, (this.data.isSydw || this.data.isYiShi), this.data.getIdentity, '', '', this.data.book, 'chaxun')
                    this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'))
                }
            } else {
                if ((!this.data.user.user.gwlb || this.data.user.user.gwlb == 'null' || this.data.user.user.gwlb == 'null ' || this.data.user.user.gwlb == '') && this.data.isSydw) {
                    this.setData({
                        bookDetails_box: 1
                    })
                } else {
                    await app.methods.updateuserCX(this.data.myPhone, this.data.options.actid, this.data.name1, (this.data.isSydw || this.data.isYiShi), this.data.getIdentity, '', '', 'chaxun', '', this.data.user.user)
                    this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'))
                }
            }
        }
        xhs.showLoading({
            title: '数据加载完毕！',
        })
        setTimeout(function () {
            xhs.hideLoading()
        }, 1000)
        console.log(this.data)
        this.setData({
            isiPhone: app.globalData.isiPhone
        })
        // console.log(app.globalData.isiPhone)
        // console.log(this.data)
    },
    // 加载内容
    async getHdInfo(_id) {
        return new Promise((resolve) => {
            hbappRequest({
                url: "/hbqt/web/index.php/Contactus/xcxhd/ziliao_lists?callback=&",
                method: "GET",
                dataType: "jsonp",
                data: {
                    _id: _id,
                    shijian: Date.parse(new Date()) / 1e3
                },
            }).then(res => {
                let newStr1 = app.methods.getAPIReturn(res);
                let actid = (this.data.options.actid && this.data.options.actid != 'undefined') ? this.data.options.actid : newStr1.data.actid;
                let options = this.data.options;
                options.actid = actid;
                this.setData({
                    actid,
                    options,
                    wenda: JSON.parse(app.methods.htmlDecodeByRegExp(newStr1.data.database)),
                    shai: JSON.parse(app.methods.htmlDecodeByRegExp(newStr1.data.database)),
                    name: app.methods.htmlDecodeByRegExp(newStr1.data.name),
                    name1: app.methods.htmlDecodeByRegExp(newStr1.data.name),
                    fp: newStr1.data.fp,
                    fpimg: newStr1.data.fpimg,
                    btn: newStr1.data.btn,
                    htImg: newStr1.data.htImg,
                    dyxx: newStr1.data.dyxx,
                    bj_img: newStr1.data.bj_img,
                })
                app.globalData.laiyuan = this.data.name
                if (this.data.fp == 'n' && newStr1.data.fpimg != '') {
                    this.setData({
                        addFriends: true,
                        huashu: newStr1.data.fpimg
                    })
                }
                if (this.data._id.indexOf('gkbps') >= 0) {
                    this.setData({
                        bpslunbo: true
                    })
                }
                resolve()
            }).catch(err => {
                console.log(err)
                resolve()
            })
        })
    },
    // 加载内容
    async getShareInfo(_id) {
        return new Promise((resolve) => {
            jiatuiRequest({
                url: "/api/v1/database/findDatabaseController",
                method: 'GET',
                dataType: 'jsonp',
                header: {
                    'X-Requested-From': 'WeChatMiniProgram'
                },
                data: {
                    _id: _id,
                    Requested: 'WeChatMiniProgram'
                },
            }).then(res => {
                if(res.statusCode == 200) {
                    let { shareImg, shareFont } = JSON.parse(res.data).data.lists[0];
                    if(shareImg) this.setData({
                        shareImg,
                        shareFont,
                    })
                }
                resolve()
            }).catch(err => {
                console.log(err)
                resolve()
            })
        })
    },
    // 该怎么就怎么
    async thisMethod() {
        if (!this.data.user) {
            if ((this.data.isSydw || this.data.isYiShi) && this.data.myPhone != '') {
                this.setData({
                    bookDetails_box: 1
                })
            } else if ((!this.data.isSydw || !this.data.isYiShi) && this.data.myPhone) {
                await app.methods.registerCX(this.data.myPhone, this.data.options.actid, this.data.name1, (this.data.isSydw || this.data.isYiShi), this.data.getIdentity, '', '', this.data.book, 'chaxun')
                this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'))
            }
        } else {
            if ((!this.data.user.user.gwlb || this.data.user.user.gwlb == 'null' || this.data.user.user.gwlb == 'null ' || this.data.user.user.gwlb == '') && (this.data.isSydw || this.data.isYiShi)) {
                this.setData({
                    bookDetails_box: 1
                })
            } else {
                // console.log(this.data.book)
                await app.methods.updateuserCX(this.data.myPhone, this.data.options.actid, this.data.name1, (this.data.isSydw || this.data.isYiShi), this.data.getIdentity, this.data.user.user.gwlb, '', 'chaxun', this.data.book, this.data.user.user)
                this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'))
            }
        }
    },
    // 选择岗位
    async choiceGw(e) {
        // console.log(this.data)
        if (this.data.myPhone) {
            if (this.data.user == undefined || !this.data.user) {
                await app.methods.registerCX(this.data.myPhone, this.data.options.actid, this.data.name1, (this.data.isSydw || this.data.isYiShi), this.data.getIdentity, e.currentTarget.dataset.gwlb, '', this.data.book, 'chaxun')
            } else {
                await app.methods.updateuserCX(this.data.myPhone, this.data.options.actid, this.data.name1, (this.data.isSydw || this.data.isYiShi), this.data.getIdentity, e.currentTarget.dataset.gwlb, '', 'chaxun', this.data.book, this.data.user.user)
            }
            this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'))
        } else {
            this.setData({
                isShowAuth: !0
            })
        }
        this.setData({
            bookDetails_box: !1,
        })
    },
    // 关注公众号
    gzgzh: function () {
        this.setData({
            modal_box0222: !0,
        })
    },
    // 预览图片
    preview(event) {
        // console.log(event.currentTarget.dataset.src)
        let currentUrl = event.currentTarget.dataset.src
        let urls = [];
        urls[0] = currentUrl;
        xhs.previewImage({
            current: currentUrl, // 当前显示图片的http链接
            urls: urls, // 需要预览的图片http链接列表
            showmenu: true,
        })
    },
    // 打开资料
    async openArticle(e) {
        if(!this.data.myPhone) {
            this.setData({
                isShowAuth: !0,
            });
            return false;
        }
        let { id, title, type, url, is_down, appid } = e.currentTarget.dataset;
        this.setData({
            book: title
        })
        if(type == 'pdf' || type == 'qita' || type == 'html') {
            if((type == 'pdf' && is_down == 0) || type == 'html') {
                xhs.navigateTo({
                    url: '/pages/zixun/zixun?src=' + url + '&title=' + title + '&type=' + type + '&_id=' + this.data.options._id + '&gh=' + this.data.options.gh + '&fx=' + this.data.options.fx,
                })
            } else if(/files.offcn.com/.test(url)) {
                xhs.navigateTo({
                    url: `/packageA/download/download?name=${title}&url=${url}&type=file`
                })
            } else {
                xhs.showToast({
                  title: '文件异常，请联系客服~',
                  icon: 'error',
                  duration: 2000
                })
            }
        } else {
            if(type == 'xcx') {
                String.prototype.replaceAll = function (s1, s2) {
                    return this.replace(new RegExp(s1, "gm"), s2);
                }
                url = url.replaceAll('&amp;', '&');
                url += `&gh=${this.data.options.gh}&fx=${this.data.options.fx}&wxh=${this.data.options.wxh}`
                xhs.navigateTo({
                    url,
                })
            } else if(type == '19xcx') {
                let { owner, orgn, erp } = this.data.getIdentity
                erp = erp ? erp : 12;
                orgn = orgn ? orgn : 13;
                owner = owner ? owner : 20588;
                if(url.indexOf('&') >= 0) {
                  url = url.substring(0, url.indexOf('&'))
                }
                url = `${url}&owner=${owner}&orgn=${orgn}&erp=${erp}`
                xhs.navigateToMiniProgram({
                    appId: appid,
                    path: url, //打开的页面路径，如果为空则打开首页
                    extraData: {
                        foo: 'bar' //需要传递给目标小程序的数据，目标小程序可在 App.onLaunch，App.onShow 中获取到这份数据
                    },
                    envVersion: 'release', //要打开的小程序版本。仅在当前小程序为开发版或体验版时此参数有效。如果当前小程序是正式版，则打开的小程序必定是正式版。
                    success(res) {
                        // 打开成功
                    }
                })
            }
        }
        this.thisMethod()
    },
    gotogzh: function () {
        console.log(111)
        this.setData({
            modal_box0222: true,
        })
    },
    closemodal: function () {
        this.setData({
            modal_box0222: false,
        })
    },
    wxToPromise(method, opt) {
        return new Promise((resolve, reject) => {
            wx[method]({
                ...opt,
                success(res) {
                    // console.log(res)
                    opt.success && opt.success();
                    resolve(res)
                },
                fail(err) {
                    // console.log(err)
                    opt.fail && opt.fail();
                    reject(err)
                }
            })
        });
    },
    // 保存图片
    saveewm0222() {
        this.wxToPromise('downloadFile', {
                url: this.data.getIdentity.files_wxurl + this.data.getIdentity.files_wxpath
            })
            .then(res => this.wxToPromise('saveImageToPhotosAlbum', {
                filePath: res.tempFilePath
            }))
            .then(res => {
                // console.log(res)
                // do something
                xhs.showToast({
                    title: '保存成功~',
                    icon: 'success',
                    duration: 2000
                });
                this.closemodal()
            })
            .catch(err => {
                // console.log(err);
                if(err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
                  xhs.showToast({
                    title: '您取消了保存',
                    icon: 'error',
                    duration: 2000
                  });
                } else {
                  xhs.showToast({
                    title: '保存失败~',
                    icon: 'error',
                    duration: 2000
                  });
                }
                this.closemodal()
            })
    },
    getseetting0222: function (res) {
        // console.log(res)
        if (res.detail.authSetting['scope.writePhotosAlbum'] == true) {
            this.saveewm0222();
            this.setData({
                userauth: false
            })
        } else {
            this.setData({
                userauth: false
            })
            xhs.showToast({
                title: '保存到相册授权未打开！',
                icon: 'none'
            })
        }

    },
    //拉起二次授权时用户选择取消
    cancelsetting: function (e) {
        this.setData({
            userauth: false
        })
        xhs.showToast({
            title: '您未授权',
            icon: 'none',
            duration: 1000
        })
    },
    async user_login(e){
        if(typeof e.detail == 'boolean') {
            this.setData({
                isShowAuth: e.detail
            })
        } else {
            this.setData({
                myPhone: e.detail
            })
            this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'));
            if (!this.data.user) {
                if (this.data.isSydw) {
                    this.setData({
                        bookDetails_box: 1
                    })
                } else {
                    await app.methods.registerCX(this.data.myPhone, this.data.options.actid, this.data.name1, (this.data.isSydw || this.data.isYiShi), this.data.getIdentity, '', '', this.data.book, 'chaxun')
                    this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'))
                }
            } else {
                if ((!this.data.user.user.gwlb || this.data.user.user.gwlb == 'null' || this.data.user.user.gwlb == 'null ' || this.data.user.user.gwlb == '') && this.data.isSydw) {
                    this.setData({
                        bookDetails_box: 1
                    })
                } else {
                    await app.methods.updateuserCX(this.data.myPhone, this.data.options.actid, this.data.name1, (this.data.isSydw || this.data.isYiShi), this.data.getIdentity, '', '', 'chaxun', '', this.data.user.user)
                    this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'))
                }
            }
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            title: this.data.shareFont ? this.data.shareFont : this.data.name,
            path: `/pages/database/database?id=${this.data.options.id}&fx=${this.data.options.fx}&gh=${this.data.options.gh}`,
            imageUrl: this.data.shareImg ? this.data.shareImg : '',
        }
    }
})